<?php

namespace app\zyhsapi\controller\v5;

use app\aliyun\controller\AliyunFilterWord;
use app\common\lib\Util;
use app\zyhsapi\controller\ZyhsAuth;
use app\zyhsapi\model\comment\ZyhsArticleGood;
use app\zyhsapi\model\comment\ZyhsArticleMyInteracted;
use app\zyhsapi\model\comment\ZyhsNoComment;
use app\zyhsapi\model\ZyhsAstrBindUser;
use app\zyhsapi\model\ZyhsInteractiveMessage;
use app\zyhsapi\model\ZyhsPxyzUserQuestion;
use app\zyhsapi\model\ZyhsRecode;
use think\Env;
use think\response\Json;

class Pxyz extends ZyhsAuth
{
    /**
     * @return Json
     */
    public function getPxyzArticleIntro()
    {
        $avatarData = $this->getRandomAvatarAndNickname(true);

        $data = [
            'avatar' => $avatarData['avatar'],
            'avatar_id' => $avatarData['avatar_id'],
            'nickname' => $avatarData['nickname'],
            'content_placeholder' => '描述你遇到的人和事，看看平行时空里的TA，遇到和你相同的情况时，TA会怎么做？',
            'add_recode_tip' => '(星盘信息便于咨询师回复，仅咨询师可查看)',
            'intro_data' => [
                'icon' => '/zyhsapp/pxyz/pxyz_tip.png',
                'title' => '#平行时空告示贴#',
                'desc' => "每个人都是独特的个体，也因此都应该被尊重！\r\n但是不同的经历和后天塑造，会有不同的思维和行动方式。\r\n当你迷茫、无助时，不如来看看平行时空里的TA会怎么选择。",
            ],
        ];

        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 获取随机头像和昵称
     * @param $isPrivate
     * @return array|Json
     */
    public function getRandomAvatarAndNickname($isPrivate = false)
    {
        $config = config('pxyz');

        $avatarId = array_rand($config['avatar_list'], 1);
        $nickname = $config['nicknames'][array_rand($config['nicknames'], 1)];
        $avatar = $config['avatar_list'][$avatarId];

        $data = [
            'avatar' => $avatar,
            'avatar_id' => $avatarId,
            'nickname' => $nickname,
        ];

        if ($isPrivate)
        {
            return $data;
        }

        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 发布内容
     * @return Json
     * @throws \Exception
     */
    public function publishContent()
    {
        $content = input('content/s', '');
        $imgs = input('imgs/s', '');
        $rid1 = input('rid1/d', 0);
        $rid2 = input('rid2/d', 0);
        $nickname = input('nickname/s', '');
        $avatarId = input('avatar_id/d', 0);

        if (!in_array($avatarId, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], true) || empty($nickname) || empty($content))
        {
            return show(config('code.error'), '请求异常，请重试～');
        }
        $config = config('pxyz');
        if (!in_array($nickname, $config['nicknames'], true))
        {
            return show(config('code.error'), '请求异常，昵称不合法～');
        }
        if (mb_strlen($content) < 12)
        {
            return show(config('code.error'), '发布的内容最少输入12字～');
        }
        if (mb_strlen($content) > 180)
        {
            return show(config('code.error'), '发布的内容最多输入180字～');
        }
        if (Util::commentCheck($this->user['id'], [
            'action' => 'publishContent', 'content' => $content,
            'imgs' => $imgs, 'rid1' => $rid1, 'rid2' => $rid2,
            'nickname' => $nickname, 'avatar_id' => $avatarId,
        ]))
        {
            return show(config('code.error'), '请求频繁，请稍后再试～');
        }
        //禁言判断
        $noCommentList = (new ZyhsNoComment())->getNoCommentList(1);
        if (in_array($this->user['id'], $noCommentList, true))
        {
            return show(config('code.error'), '你已被禁言，不可发布内容');
        }
        // 获取 用户绑定咨询师信息
        $userBindAstrInfo = (new ZyhsAstrBindUser())->getAstrBindUserData();
        if (isset($userBindAstrInfo[$this->user['id']]))
        {
            return show(config('code.error'), '占星师身份，不可发布内容');
        }
        //发布内容进行 内容安全检测
        $res = AliyunFilterWord::checkText($content, 'question_pic_check');
        //若内容有违规且超过配置的相似比例，则进行隐藏不显示，将标签存入库中
        if ($res)
        {
            return show(201, '问题中有敏感词');
        }
        if ($imgs)
        {
            $imgList = json_decode($imgs, true);
            if (count($imgList) > 2)
            {
                return show(config('code.error'), '图片最多添加2张～');
            }
            //图片进行 内容安全检测
            //对图片进行校验
            $ossHost = Env::get('host.photo');
            foreach ($imgList as $photo)
            {
                $res = AliyunFilterWord::checkImg(1, $ossHost . $photo, 'question_pic_check');

                if ($res['status'] === false)
                {
                    return show(201, '图片包含' . $res['text']);
                }
            }
        }
        $recodeModel = new ZyhsRecode();
        $recodeBack = [];
        if ($rid1)
        {
            $recodeInfo1 = $recodeModel->getInfoById($rid1);
            if (!$recodeInfo1 || $recodeInfo1['uid'] != $this->user['id'])
            {
                return show(config('code.error'), '服务异常，档案不存在～');
            }
            $recodeBack['recode1'] = [
                'id' => $rid1,
                'avatar' => $recodeInfo1['avatar'],
                "name" => $recodeInfo1['name'],
                "type" => (int)$recodeInfo1['type'],
                "year" => (int)$recodeInfo1['year'],
                "month" => (int)$recodeInfo1['month'],
                "day" => (int)$recodeInfo1['day'],
                "hour" => (int)$recodeInfo1['hour'],
                "minute" => (int)$recodeInfo1['minute'],
                "timezone" => (int)$recodeInfo1['timezone'],
                "long_deg" => (int)$recodeInfo1['long_deg'],
                "long_min" => (int)$recodeInfo1['long_min'],
                "ew" => (int)$recodeInfo1['ew'],
                "lat_deg" => (int)$recodeInfo1['lat_deg'],
                "lat_min" => (int)$recodeInfo1['lat_min'],
                "ns" => (int)$recodeInfo1['ns'],
                "is_summer" => (int)$recodeInfo1['is_summer'],
                "birth_country" => $recodeInfo1['birth_country'],
                "birth_province" => $recodeInfo1['birth_province'],
                "birth_city" => $recodeInfo1['birth_city'],
                "live_country" => $recodeInfo1['live_country'],
                "live_province" => $recodeInfo1['live_province'],
                "live_city" => $recodeInfo1['live_city'],
                "isself" => (int)$recodeInfo1['isself'],
            ];
            if ($rid2)
            {
                $recodeInfo2 = $recodeModel->getInfoById($rid2);
                if (!$recodeInfo2 || $recodeInfo2['uid'] != $this->user['id'])
                {
                    return show(config('code.error'), '服务异常，档案不存在～');
                }
                $recodeBack['recode2'] = [
                    'id' => $rid1,
                    'avatar' => $recodeInfo2['avatar'],
                    "name" => $recodeInfo2['name'],
                    "type" => (int)$recodeInfo2['type'],
                    "year" => (int)$recodeInfo2['year'],
                    "month" => (int)$recodeInfo2['month'],
                    "day" => (int)$recodeInfo2['day'],
                    "hour" => (int)$recodeInfo2['hour'],
                    "minute" => (int)$recodeInfo2['minute'],
                    "timezone" => (int)$recodeInfo2['timezone'],
                    "long_deg" => (int)$recodeInfo2['long_deg'],
                    "long_min" => (int)$recodeInfo2['long_min'],
                    "ew" => (int)$recodeInfo2['ew'],
                    "lat_deg" => (int)$recodeInfo2['lat_deg'],
                    "lat_min" => (int)$recodeInfo2['lat_min'],
                    "ns" => (int)$recodeInfo2['ns'],
                    "is_summer" => (int)$recodeInfo2['is_summer'],
                    "birth_country" => $recodeInfo2['birth_country'],
                    "birth_province" => $recodeInfo2['birth_province'],
                    "birth_city" => $recodeInfo2['birth_city'],
                    "live_country" => $recodeInfo2['live_country'],
                    "live_province" => $recodeInfo2['live_province'],
                    "live_city" => $recodeInfo2['live_city'],
                    "isself" => (int)$recodeInfo2['isself'],
                ];
            }
        }

        $insertData = [
            'uid' => $this->user['id'],
            'avatar_id' => $avatarId,
            'nickname' => $nickname,
            'status' => 1,
            'content' => $content,
            'imgs' => $imgs,
            'rid1' => $rid1,
            'rid2' => $rid2,
            'recode_data' => $recodeBack,
            'create_time' => $this->request->time(),
        ];

        try
        {
            $id = (new ZyhsPxyzUserQuestion())->SaveData($this->user['id'], $insertData);

            return show(config('code.success'), '请求成功', ['id' => $id]);
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);

            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 平行宇宙 首页
     * @return Json
     * @throws \Exception
     */
    public function index()
    {
        $type = input('type/d', 1);
        $page = input('page/d', 1);
        if (!in_array($type, [1, 2], true) || $page <= 0)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $resData = (new ZyhsPxyzUserQuestion())->getIndexList($this->user['id'] ?? 0, $type, $page, 10);

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 我的发布详情
     * @return Json
     * @throws \Exception
     */
    public function getContentDetail()
    {
        $id = input('id/d', 0);
        if (!$id)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $zyhsPxyzUserQuestionModel = new ZyhsPxyzUserQuestion();
        $contentInfo = $zyhsPxyzUserQuestionModel->getInfoById($id);
        if (!$contentInfo || $contentInfo['status'] !== 1)
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        $recodeData = null;
        $userBindAstrInfo = (new ZyhsAstrBindUser())->getAstrBindUserData();
        $goodIds = $this->user ? (new ZyhsArticleGood())->getUserGoodAids($this->user['id'], 1) : [];
        if ($contentInfo['rid1'])
        {
            $recodeData = [
                'icon' => '/zyhsapp/pxyz/astro_icon.png',
                'name' => $contentInfo['rid2'] ? '双人星盘' : '单人星盘',
                'target' => 'local',
                'link' => 'empty',
            ];
            if ($this->user['id'] === $contentInfo['uid'])
            {   // 本人
                $recodeData['target'] = 'toast';
                $recodeData['link'] = '仅支持占星师查看星盘';
            } else
            {
                if (isset($userBindAstrInfo[$this->user['id']]))
                {   // 咨询师
                    $recodeData['link'] = "other_astrolable?atype=1&aid={$id}&rid1={$contentInfo['rid1']}&rid2={$contentInfo['rid2']}&need_auth=2";
                }
            }
        }
        $userDes = '宇宙神秘人';
        if ($this->user['rid'])
        {
            $utilModel = new Util();
            $recodeInfo = (new ZyhsRecode())->getInfoById($this->user['rid']);
            $userDes = '日' . $utilModel->recodeAstroShorthand($recodeInfo['sun']) . '月' . $utilModel->recodeAstroShorthand($recodeInfo['moon']) . '升' . $utilModel->recodeAstroShorthand($recodeInfo['asc']);
        }
        //  增加 已读数
        $zyhsPxyzUserQuestionModel->updateCommentNumData($id, 'read_num', [
            'good_num' => $contentInfo['good_num'],    // 点赞数
            'comment_num' => $contentInfo['comment_num'], // 评论总数
            'read_num' => $contentInfo['read_num'],    // 已读总数
        ], 1);

        $avatarNicknameConfig = config('pxyz');
        $data = [
            'nickname' => $contentInfo['nickname'],
            'avatar' => $avatarNicknameConfig['avatar_list'][$contentInfo['avatar_id']],
            'create_time' => Util::timeToStr($contentInfo['create_time']),
            'user_des' => $userDes,
            'astr_reply_num' => $contentInfo['astr_reply_num'],
            'content' => $contentInfo['content'],
            'img_list' => $contentInfo['imgs'],
            'recode_data' => $recodeData,
            'good_num' => $contentInfo['good_num'],
            'is_self' => $this->user['id'] === $contentInfo['uid'] ? 1 : 0,
            'is_good' => in_array($id, $goodIds, true) ? 1 : 0, // 是否 点赞
            'auth' => isset($userBindAstrInfo[$this->user['id']]) ? 1 : 0,
            'comment_num' => $contentInfo['comment_num'],
        ];

        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 点赞我的发布
     * @return Json
     * @throws \Exception
     */
    public function zan()
    {
        $id = input('id/d', 0);
        $status = input('status/d', 1);
        if ($id <= 0 || !in_array($status, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $zyhsPxyzUserQuestionModel = new ZyhsPxyzUserQuestion();
        $contentInfo = $zyhsPxyzUserQuestionModel->getInfoById($id, ['status', 'uid', 'good_num', 'read_num', 'comment_num']);
        if (!$contentInfo || $contentInfo['status'] !== 1)
        {
            return show(config('code.error'), '服务异常，内容不存在～');
        }
        $zyhsArticleGoodModel = new ZyhsArticleGood();
        $goodIds = $zyhsArticleGoodModel->getUserGoodAids($this->user['id'], 1);
        if ($status === 1)
        {   // 点赞
            if (in_array($id, $goodIds, true))
            {
                return show(config('code.success'), '点赞成功');
            }
            $data = [
                'atype' => 1,
                'aid' => $id,
                'uid' => $this->user['id'],
                'uid2' => $contentInfo['uid'],
                'create_time' => $this->request->time(),
            ];
            $resData = $zyhsArticleGoodModel->addZan($data);
        } else
        {
            if (!in_array($id, $goodIds, true))
            {
                return show(config('code.success'), '取消点赞成功');
            }
            $data = [
                'atype' => 1,
                'aid' => $id,
                'uid' => $this->user['id'],
            ];
            $resData = $zyhsArticleGoodModel->delZan($data);
        }
        if ($resData)
        {
            $inc = $status === 1 ? 1 : -1;
            $zyhsPxyzUserQuestionModel->updateCommentNumData($id, 'good_num', [
                'good_num' => $contentInfo['good_num'],
                'read_num' => $contentInfo['read_num'],
                'comment_num' => $contentInfo['comment_num'],
            ], $inc);
            if ($contentInfo['uid'] !== $this->user['id'])
            {   //  不是自己给自己点赞的情况    添加 点赞 互动消息
                (new ZyhsInteractiveMessage())->setZanInteractiveMessage(1, $id, 1, $contentInfo['uid'], $this->user['id'], 0);
            }
            return show(config('code.success'), $status === 1 ? '点赞成功' : '取消点赞成功');
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 我的 发布
     * @return Json
     * @throws \Exception
     */
    public function myPublish()
    {
        $page = input('page/d', 1);
        if ($page < 1)
        {
            $page = 1;
        }

        $resData = (new ZyhsPxyzUserQuestion())->getMyPublishData($this->user['id'], $page, 10);

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 删除 我的 发布
     * @return Json
     * @throws \Exception
     */
    public function delPublish()
    {
        $id = input('id/d', 0);
        if (!$id)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        $zyhsPxyzUserQuestionModel = new ZyhsPxyzUserQuestion();
        $contentInfo = $zyhsPxyzUserQuestionModel->getInfoById($id, ['status', 'uid', 'is_top', 'is_recommend']);
        if (!$contentInfo || $contentInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，内容不存在～');
        }
        if ($contentInfo['status'] !== 1)
        {
            return show(config('code.success'), '删除成功');
        }
        $res = $zyhsPxyzUserQuestionModel->delData($id, $this->user['id'], $contentInfo['is_top'] === 1, $contentInfo['is_recommend'] === 1);

        if ($res)
        {
            return show(config('code.success'), '删除成功');
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 我参与的
     * @return Json
     * @throws \Exception
     */
    public function myInteracted()
    {
        $page = input('page/d', 1);
        if ($page < 1)
        {
            $page = 1;
        }

        $pageData = (new ZyhsArticleMyInteracted())->getMyInteractedPageList($this->user['id'], 1, $page, 10);

        if ($pageData['data'])
        {
            $aids = array_keys($pageData['data']);

            $contentList = (new ZyhsPxyzUserQuestion())->batchGetInfoByIds($aids, ['content', 'astr_reply_num', 'good_num', 'comment_num', 'status']);
            $dataList = [];
            foreach ($pageData['data'] as $aidItem => $interactionTime)
            {
                if (!isset($contentList[$aidItem]))
                {
                    continue;
                }
                $dataItem = $contentList[$aidItem];
                // $desc = '3咨询师 · 19评论 · 132鼓励 | 暂无互动';
                $desc = '';
                if ($dataItem['astr_reply_num'])
                {
                    $desc = "{$dataItem['astr_reply_num']}咨询师";
                }
                if ($dataItem['comment_num'])
                {
                    $desc .= (empty($desc) ? '' : ' · ') . "{$dataItem['comment_num']}评论";
                }
                if ($dataItem['good_num'])
                {
                    $desc .= (empty($desc) ? '' : ' · ') . "{$dataItem['good_num']}鼓励";
                }
                if ($dataItem['status'] === 1)
                {
                    $target = 'local';
                    $link = "community_detail?id={$aidItem}&need_auth=2";
                } else
                {
                    $target = 'toast';
                    $link = '该内容已删除';
                }

                $dataList[] = [
                    'title' => $dataItem['content'],
                    'des' => $desc ?: '暂无互动',
                    'create_time' => Util::timeToStr((int)$interactionTime),
                    'id' => $aidItem,
                    'target' => $target,
                    'link' => $link,
                ];
            }

            $pageData['data'] = $dataList;
        }

        return show(config('code.success'), '请求成功', $pageData);
    }
}
